const cp = require('child_process')
const { resolve } = require('path')
const mongoose = require('mongoose')
const Movie = mongoose.model('Movie')

;
(async() => {
    // 脚本地址
    const script = resolve(__dirname, '../crawler/trailer-list')

    //生成子进程 
    child = cp.fork(script, [])
    let invoked = false

    child.on('error', err => {
        if (invoked) return
        invoked = true
        console.log(err)
    })

    //进程退出时
    child.on('exit', code => {
        if (invoked) return
        invoked = false

        let err = code === 0 ? null : new Error('exit code ' + code)

        console.log(err)
    })

    child.on('message', data => {
        let result = data.result


        result.forEach(async item => {
            let movie = await Movie.findOne({
                doubanId: item.doubanId
            })


            if (!movie) {
                movie = new Movie(item)
                await movie.save()
            }
        })
        console.log('----------------task movie--------------')
        console.log(result)
    })




})()